//
//  LauMainViewController.swift
//  SwiftProject
//
//  Created by Lausen on 2017/7/9.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit
import SVProgressHUD

class LauMainViewController: UITabBarController {

    fileprivate var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildViewControllers()
        setupComposeButton()
        setupTimer()
        
        //加载新特性的方法
        setupNewFeatureView()
        
        ///设置tabBarController的代理
        delegate = self
        
        ///注册一个通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: LauUserShouldLoginNotification), object: nil)
    }

    
    //MARK: -- 登录按钮发送通知的响应
    @objc private func userLogin(n: Notification){
        
        var when = DispatchTime.now()
        
        //这个是token过期的发送的通知
        if n.object != nil {
            
            //设置提示框的样式是灰色的
            SVProgressHUD.setDefaultMaskType(.black)
            
            //提示框提示语
            SVProgressHUD.showInfo(withStatus: "账户信息过期了,需要重新登录!")
            
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            
            SVProgressHUD.setDefaultMaskType(.clear)
            
            let naviVC = UINavigationController(rootViewController: LauOAuthViewController())
            
            self.present(naviVC, animated: true, completion: nil)
        }
    }
    
    //MARK: -- 析构函数,销毁时钟,移除通知
    deinit {
        
        // 销毁时钟
        timer?.invalidate()
        
        //移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
    /*
     portrait   :竖屏,肖像
     landscape  :横屏,风景画
     如果调用了这个方法,那么当前控制器的子控制器,同样也是只支持竖屏,
     如果想要设置其他支持横屏(比如:播放视屏)那么就要通过model控制器来实现横屏
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
    
        return .portrait
    }
    
    //MARK: -- 撰写按钮的点击事件
    //1:使用fileprivate可以让方法私有化,
    //@objc的作用:允许这个函数在'运行时'通过OC的消息机制被调用
    @objc fileprivate func composeStatus() -> (){
        
        print("按钮的点击事件")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //懒加载一个按钮
    fileprivate lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}

// MARK: - 设置新特性或者是欢迎界面的分类
extension LauMainViewController{
    //MARK: -- 设置新特性的方法
    fileprivate func setupNewFeatureView(){
        
        //1:根据是否登录来判定是否需要显示新特性/欢迎界面   没有登录就直接退出
        if !LauNetworkManager.shared.userLogon {
            
            return
        }
        
        //2:根据是否是新版本,判定需要接在的界面
        let v = isNewFeature ? LauNewFeatureView.newFeatureView() : LauWelcomeView.welcomeView()
        
        view.addSubview(v)
    }
    
    //MARK: -- 利用分类里面的计算性属性来判定是否是新特性
    private var isNewFeature: Bool{
        
        //1:获取当前的info.plist里面的版本
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
        
        //2:获取存放在document里面的版本号,(最好放在偏好设置里面去,)
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        
        let version = try? String(contentsOfFile: path)
        
        //3:如果当前的版本号与存放在沙盒里面的版本号不一致,将当前的版本号存放到沙盒里面去
        if currentVersion != version {
            
            try? currentVersion?.write(toFile: path, atomically: true, encoding: .utf8)
            
            return true
        }
        
        return false
    }
}

// MARK: - UITabBarControllerDelegate tabBarController的代理方法
extension LauMainViewController:UITabBarControllerDelegate{
    
    /// 将要切换tabBaritems时调用的方法
    ///
    /// - Parameters:
    ///   - tabBarController: 当前的tabBarController
    ///   - viewController: 将要切换的控制器
    /// - Returns: 是否要切换
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        /// 获取将要跳转的控制器的index
        let index = (childViewControllers as NSArray).index(of: viewController)
        
        /// 如果将要跳转的是首页,并且现在已经是在首页了,那么就
        if index == 0 && index == selectedIndex {
            
            //1:获取将要跳转的导航控制器
            let naviVC = viewController as! LauNavigationController
            //2:获取导航控制器的第一个子控制器
            let vc = naviVC.childViewControllers[index] as! LauHomeViewController
            //3:设置tableView滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0,y: -64), animated: true)
            
            //4:刷新数据
            /*
             在这里要加上个延时,否则滚动不到顶部,可能是因为一边滚动,一边刷新数据导致的
             */
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                
                vc.loadData()
            })
            
            //清空item和icon上面的数字
            self.tabBar.items?[0].badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
            
        }
        
        //如果是UIViewController的类(不包括子类)就不切换控制器
        return !viewController.isMember(of: UIViewController.self)
    }
}

// MARK: - 专门用来做时钟的分类
extension LauMainViewController{
    
    /// 实例化时钟的方法
    fileprivate func setupTimer() {
        
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(requestUnreadConut), userInfo: nil, repeats: true)
    }
    
    /// 调用请求未读微博的条数和设置badage
    @objc private func requestUnreadConut(){
        
        if !LauNetworkManager.shared.userLogon {
            
            return
        }
    
        LauNetworkManager.shared.unreadCount { (count) in
         
// MARK: - 如果count大于0,就显示条数,如果等于0的时候,就直接赋值nil.这样可以避免出现红圆圈
            self.tabBar.items?[0].badgeValue =  count > 0 ? "\(count)" : nil
            
            //设置icon的图标的提示未读数
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

//extension类似于OC中的分类,在Swift中还可以用来切分代码块
//可以把相近功能的函数,放在一个Extension中
//便于代码维护
//注意:和OC中的分类一样,extension中不能定义属性
//MARK: -- 添加自控制器
extension LauMainViewController{
    
    fileprivate func setupComposeButton(){
        
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(viewControllers?.count  ?? 0)
        
        //因为有一个点的容错点,所以要减去1
        let w = tabBar.bounds.width / count
        
        //insetBy对应OC里面的CGRectInSet,整数向内缩进,负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        //添加撰写按钮的点击事件
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    fileprivate func setupChildViewControllers(){
        
        //0:获取沙盒保存文件的路径
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let dataPath = (path as NSString).appendingPathComponent("main.json")
        
        var data = NSData(contentsOfFile: dataPath)
        
        //0.5:如果沙盒的二进制数据为空的话,就从bundle加载json文件
        if data == nil {
            
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            
            data = NSData(contentsOfFile: path!)
        }
        
        //1:获取设置控制器的信息字典
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]
            else{
               
            return
        }
        
        //2:遍历字典,调用生成控制器的方法
        var arrayM = [UIViewController]()
        for dict in array ?? [[String: AnyObject]]() {
            
            arrayM.append(controller(dict: dict))
        }
        
        //3:设置viewControllers
        viewControllers = arrayM
    }
    
    /// 设置自控制器的属性
    ///
    /// - Parameter dict: [clsName,title,imageName]
    /// - Returns: UIViewController
    private func controller(dict:[String: Any]) -> UIViewController{
        
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
        let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? LauBaseViewController.Type,
        let vistorInfoDict = dict["vistorInfo"] as? [String :String]
        else {
            
            return UIViewController()
        }
        
        //1:设置控制器的title
        let vc = cls.init()
        
        vc.title = title
        
        vc.vistorInfoDict = vistorInfoDict
        
        //2:设置tabBar的image
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        
        //3:设置tabBar的标题
        /**
         值得注意的是:设置颜色.设置高亮可以,但是设置字体的大小,如果设置高亮状态的话,是没有效果的
         */
        vc.tabBarItem.setTitleTextAttributes(
            [NSForegroundColorAttributeName: UIColor.orange],
            for: .selected)
        //设置字体的大小需要设置到普通状态下,才会有效果
        vc.tabBarItem.setTitleTextAttributes(
            [NSFontAttributeName: UIFont.systemFont(ofSize: 12)],
            for: .normal)
        
        ///每次加入一个导航控制器,都会调用一次pushViewController方法
        let navi = LauNavigationController(rootViewController: vc)
        
        return navi
    }
}
